using System;
using webapi_Domain.Repository;
using webapi_Domain;
using webapi_infrastructure.Db;
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Threading.Tasks;


namespace webapi_infrastructure.Repository
{
    public class RepositoryBase<T> : IRepositoryBase<T> where T : BaseEntity
    {
        //私有字段
        private readonly webDbContext _db;
        private DbSet<T> _table;//没能解决这里why no readonly ???

        //构造函数
        public RepositoryBase(webDbContext db)//添加数据库的构造函数且参数不能为null，只能这样了
        {
            _db = db;//new webDbContext(null);
            _table = _db.Set<T>();
        }


        //实现接口类属性（get/set写了{}就不需要写;号）
        public IQueryable<T> Table
        {
            get
            {
                if (_table == null)
                {
                    _table = _db.Set<T>();
                }
                return _table.AsQueryable<T>();//.AsNoTracking()
            }
            set { }
        }

        //查询
        public T GetById(Guid id)
        {
            T entity = _table.Where(x => x.Id == id).FirstOrDefault();
            return entity;
        }
        //新增
        public void Add(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            //   entity.CreatedBy = 0;
            //   entity.UpdatedBy = 0;
            entity.UpdatedAt = DateTime.Now;
            entity.DisplayOrder = 0;
            entity.Remarks = "没有评论";

            _table.Add(entity);
            _db.SaveChanges();
        }
        //编辑
        public void Update(T entity)
        {
            entity.UpdatedAt = DateTime.Now;
            _table.Update(entity);
            _db.SaveChanges();
        }
        //删除 （伪删除）
        public void Deleted(Guid id)
        {
            var entity = _table.Where(x => x.Id == id).FirstOrDefault();
            entity.IsDeleted=true;
            this.Update(entity);
            //   _table.Remove(entity);
            _db.SaveChanges();
        }


        //审计日志表的新增功能
        public async Task SaveAsync(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            // entity.CreatedBy = DateTime.Now;
            entity.UpdatedAt = DateTime.Now;
            entity.DisplayOrder = 0;

            await _db.AddAsync(entity);
            await _db.SaveChangesAsync();
        }
    }
}